function bdr_e = sort_border(V,E,ET)
% function bdr_e = sort_border(V,E,ET)
% this function is used to sort border edge in turn one-by-one connected
% the return value store the edges' index in prescribed turn
% after execute this function, we can use the following to check the
% validaty:
% ------------------------------------------------
% figure;text((V(E(bdr_e,1),1)+V(E(bdr_e,2),1))/2,  ...
%       (V(E(bdr_e,1),2)+V(E(bdr_e,2),2))/2,num2str(bdr_e));
% bdr_e'
% ------------------------------------------------
% global V posV ET posE E_more E;

% find the index of boundary edge
boundE = find(ET(:,2)==0);
% get its length
nbdr = length(boundE);
% temp boundary edge list
E_bound = E(boundE,:); 
% reserve spaces
bdr_e = zeros(nbdr,1); 
% set the first node in boundary nodes list
% begin from [0,0] and [1,0] is better.
% begin from [1,1] and [0,1] is bad.
start_node = [0,0];
start = find(abs(V(:,1)-start_node(1))<10*eps & abs(V(:,2)-start_node(2))<10*eps);
eg2 = find(E_bound(:,1)==start | E_bound(:,2)==start);
% pick the edge in clockwise turn:
eg = eg2(1);
if (V(E_bound(eg,1),2)~=0 || V(E_bound(eg,2),2)~=0)
    eg = eg2(2); % if the first edge is not on line x==1,then pick the second edge
end
% then we must seek the eg in boundE for global edge index as boundE(eg).
bdr_e(1) = boundE(eg);
% and pick the next start points
if E_bound(eg,1) == start
    start = E_bound(eg,2);  % begin from the second node of current edges
else
    start = E_bound(eg,1);
end

for i = 2:nbdr % after execute for nbdr-1 time, all the boundary nodes are found
    % we search in E_bound to keep the less search time
    eg2 = find(E_bound(:,1)==start | E_bound(:,2)==start);
    if eg2(1) ~= eg
        eg = eg2(1);
    else
        eg = eg2(2);
    end
    % then we must seek the eg in boundE for global edge index as boundE(eg).
    bdr_e(i) = boundE(eg);
    % find next start nodes
    if E_bound(eg,1)==start
        start = E_bound(eg,2);
    else
        start = E_bound(eg,1);
    end
end